import Cookies from 'js-cookie'
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import enLocale from 'element-ui/lib/locale/lang/en';
import zhLocale from 'element-ui/lib/locale/lang/zh-CN';
import { en } from './config/en';
import { zh } from './config/zh';
import { rbacEn } from '../views/rbac/language/rbac.en';
import { rbacZh } from '../views/rbac/language/rbac.zh';
import { systemEn } from '../views/system/language/system.en';
import { systemZh } from '../views/system/language/system.zh';
import { samplesEn } from '../views/samples/language/samples.en';
import { samplesZh } from '../views/samples/language/samples.zh';
import { routerEn } from '../router/language/router.en';
import { routerZh } from '../router/language/router.zh';
import { lookupsEn } from '../views/lookups/language/lookups.en';
import { lookupsZh } from '../views/lookups/language/lookups.zh';

Vue.use(VueI18n);

const DEFAULT_LANG = 'zh';
const LOCALE_KEY = 'localeLanguage';

const locales = {
  zh: Object.assign(zh, zhLocale, rbacZh, systemZh, samplesZh, routerZh, lookupsZh),
  en: Object.assign(en, enLocale, rbacEn, systemEn, samplesEn, routerEn, lookupsEn)
};

// 获取浏览器的语言偏好
const browserLang = navigator.language || navigator.userLanguage;
const localeLang = Cookies.get(LOCALE_KEY)
var currLang;
if (localeLang) {
  currLang = localeLang
} else {
  const appLang = browserLang.split('-')[0]; // 提取语言代码部分

  // 检查应用是否支持该语言，如果不支持则使用默认语言
  const supportedLangs = ['zh', 'en']; // 假设应用支持的语言列表
  if (supportedLangs.includes(appLang)) {
    currLang = appLang;
  } else {
    currLang = DEFAULT_LANG; // 使用默认语言
  }
}
Cookies.set(LOCALE_KEY, currLang)
const i18n = new VueI18n({
  locale: currLang,
  messages: locales
});

export const setup = lang => {
  if (lang === undefined) {
    lang = Cookies.get(LOCALE_KEY)
    if (locales[lang] === undefined) {
      lang = DEFAULT_LANG;
    }
  }

  Cookies.set(LOCALE_KEY, lang)
  Object.keys(locales).forEach(lang => {
    document.body.classList.remove(`lang-${lang}`);
  });
  document.body.classList.add(`lang-${lang}`);
  document.body.setAttribute('lang', lang);
  Vue.config.lang = lang;
  i18n.locale = lang;
};
window.i18n = i18n;

export default i18n;
